import uuid

from sqlalchemy import Column, Integer, String, Text, DateTime, func
from mapper.base import Base, SessionLocal


class ConversationHistory(Base):
    __tablename__ = "conversation_history"

    id = Column(Integer, primary_key=True, autoincrement=True)  # 主键，自增
    role = Column(String(50), nullable=False)  # 消息角色：user（用户）、assistant（面试官智能体）、ai（润色虚拟LLM）
    message = Column(Text, nullable=False)  # 实际消息内容
    thread_id = Column(Integer, nullable=False)  # 所属面试线程 ID（暂时不加外键约束）
    request_id = Column(String(50))  # 每条消息的请求 ID 用于追踪多轮对话时的上下文
    created_at = Column(DateTime, default=func.now())  # 消息创建时间

    def __repr__(self):
        return (
            f"<ConversationHistory(id={self.id}, role={self.role}, message={self.message}, "
            f"thread_id={self.thread_id},  created_at={self.created_at})>"
        )


def get_conversation_history_by_thread_id(thread_id, include_roles=[]):
    session = SessionLocal()
    query = session.query(ConversationHistory).filter(ConversationHistory.thread_id == thread_id)
    if include_roles:
        query = query.filter(ConversationHistory.role.in_(include_roles))
    return query.order_by(ConversationHistory.created_at).all()


def save_conversation_history(thread_id, role, message,request_id):
    session = SessionLocal()
    new_message = ConversationHistory(
        role=role,
        message=message,
        thread_id=thread_id,
        request_id=request_id
    )
    session.add(new_message)
    session.commit()
    session.close()
